//
//  YSCartCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/7/25.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//  购物篮

#import "YSCartCtrl.h"
#import "YSClubDataTool.h"
#import "YSSupplier.h"
#import "YSCartBannerView.h"
#import "YSCartBottomBar.h"
#import "YSCartCell.h"
#import "YSCartBusinessHeaderView.h"
#import <objc/runtime.h>
#import "YSAccountCenterCtrl.h"
#import "YSAccountOrderStatusCtrl.h"
#import "YSOrderViewCtrl.h"
#import "YSCartEmptyView.h"
#import "YSBusinessCtrl.h"
#import "YSProductDetailCtrl.h"
#import "YSHomeDataTool.h"
#import "YSCommonReqTool.h"


static const NSString *kCartIndexPathObj = @"kCartIndexPathObj";

@interface YSCartCtrl ()<UITableViewDataSource,UITableViewDelegate,CalcViewDelegate,YSAccountCenterDelegate,YSAccountOrderStatusDelegate>

@property (strong, nonatomic)YSCartBannerView *headerView;
@property (strong, nonatomic)YSCartBottomBar *bottomBar;

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *allFrames;

@property (strong, nonatomic) YSCartEmptyView *emptyView;

@property (strong, nonatomic) YSCartRes *result;
@property (assign, nonatomic) CGFloat allCellHeight;
@property (strong, nonatomic) UIAlertView *alert;

@property (strong, nonatomic) NSMutableString *selectProdIds;

@end

@implementation YSCartCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"购物篮"];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"nav_return_normal" highImageName:@"nav_return_normal" target:self action:@selector(back)];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(itemStatusChange:) name:kCartItemChangeNortif object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(toHomeCtrl:) name:kToHomePageNortif object:nil];
    
    _headerView = [[YSCartBannerView alloc]init];
    
    _emptyView = [YSCartEmptyView emptyView];
    [_emptyView setBackgroundColor:[UIColor clearColor]];
    [_emptyView setWidth:SCREENW];
    [_emptyView setHeight:SCREENH];
    [self.view addSubview:_emptyView];
    
    [self initTableView];
    [self initBottomBar];
    
    _allFrames = [NSMutableArray array];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(ISLOGIN){
        [self.tableView setHidden:NO];
        [self.bottomBar setHidden:NO];
        [self requestData];
    }else{
        [self.tableView setHidden:YES];
        [self.bottomBar setHidden:YES];
    }
}

-(void)refreshBottomBarStatus{
    self.bottomBar.statusBtn.selected = NO;
    [self.bottomBar setPrice:0];
}

-(void)initBottomBar{
    __weak YSCartCtrl *ctrl = self;
    _bottomBar = [YSCartBottomBar bottomBar];
    [_bottomBar setX:0];
    [_bottomBar setWidth:SCREENW];
    [_bottomBar setY:SCREENH - YSCartBottomBarHeight - NavWithStatusBarH];
    [self.view addSubview:_bottomBar];
    [_bottomBar setOperation:^{
        //select all callback
        if(ctrl.bottomBar.statusBtn.selected){
            for (YSSupplier *supplier in ctrl.result.supplierList) {
                [supplier setStatus:YES];
                for (YSCartProduct *prod in supplier.prodList) {
                    [prod setStatus:YES];
                }
            }
        }else{
            for (YSSupplier *supplier in ctrl.result.supplierList) {
                [supplier setStatus:NO];
                for (YSCartProduct *prod in supplier.prodList) {
                    [prod setStatus:NO];
                }
            }
        }
        [ctrl calcCartCurrentSelectProductWithPrice];
        [ctrl.tableView reloadData];
    }];

    [_bottomBar setToAccountCenter:^{
        
        ctrl.selectProdIds = [NSMutableString string];
        for (YSSupplier *supplier in ctrl.result.supplierList) {
            for (YSCartProduct *prod in supplier.prodList) {
                if(prod.status){
                    [ctrl.selectProdIds appendString:[NSString stringWithFormat:@"%ld,",prod.prodId]];
                }
            }
        }
        NSString *ids = nil;
        if(ctrl.selectProdIds.length){//去掉最后的逗号
            ids  = [NSMutableString stringWithString:[ctrl.selectProdIds substringToIndex:ctrl.selectProdIds.length-1]];
        }else{
            ShowTips(@"请选择要结算的商品");
            return;
        }
        
       [TalkingData trackEvent:kEventCartToAccountCenter];
        
       YSAccountCenterCtrl *accountCtrl =  [[YSAccountCenterCtrl alloc]initWithOrdreCode:nil selectProdIds:ids targetType:accountCenterFinishCartType productType:ordinaryProductType];
        [accountCtrl setDelegate:ctrl];
        [ctrl.navigationController pushViewController:accountCtrl animated:YES];
    }];
}

-(void)accountCenterFinish:(int)type status:(NSString *)status{
    if(type == accountCenterFinishCartType){
        [self toOrderStatusPage:status];
    }
}

/**
 *  结算中心页面关闭,回调跳转至支付状态页面
 *
 *  @param resultCode 状态码
 */
-(void)toOrderStatusPage:(NSString *)resultCode
{
    YSAccountOrderStatusCtrl *ctr = [YSAccountOrderStatusCtrl initWithResultCode:resultCode targetType:orderStatusFinishCartType];
    ctr.delegate = self;
    //进入状态页面
    [self.navigationController pushViewController:ctr  animated:YES];
}

/**
 *  订单状态页面关闭,回调跳转至订单列表页
 *
 *  @param type
 */
-(void)orderStatusFinish:(int)type
{
    if(orderStatusFinishCartType == type){
        CustomNavigationCtrl *nav = [[CustomNavigationCtrl alloc]initWithRootViewController:[YSOrderViewCtrl new]];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    }
}

-(void)initTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH-NavWithStatusBarH-YSCartBottomBarHeight) style:UITableViewStylePlain];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    header.lastUpdatedTimeLabel.hidden = YES;
    _tableView.header = header;
    [self.tableView setTableFooterView:[UIView new]];
    [self.tableView setBackgroundColor:PUBLIC_BG];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 50, 0, 0);
    [self.view addSubview:self.tableView];
}

-(void)headerRefresh{
     if(ISLOGIN){
         [self.tableView setHidden:NO];
         [self.bottomBar setHidden:NO];
         [self requestData];
     }else{
         [self.tableView setHidden:YES];
         [self.bottomBar setHidden:YES];
     }
}

-(void)back{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(void)requestData{
    if(ISLOGIN){
        [YSClubDataTool getCartInfo:^(YSCartRes *result) {
            [UIUtil refreshComplete:self.tableView];
            [self refreshBottomBarStatus];
            if(result.isSucc){
                [self inflateData:result];
            }else{
                if(result.code == 1001 || result.code == 1002){
                    [Utils clearExitInfo];
                    [Utils showLoginCtrl:self];
                }
                ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            [UIUtil refreshComplete:self.tableView];
            [self showEmptyView];
            ShowTips(kRequestFailure);
        }];
    }
}

-(void)showEmptyView{
    [DefaultsHelper setInteger:0 forKey:kCartIndex];
    [self.tableView setHidden:YES];
    [self.bottomBar setHidden:YES];
    [self.emptyView setHidden:NO];
}

-(void)inflateData:(YSCartRes *)result{
    _result = result;
    
    //top ad
    if(result.bannerList.count){
        [self.headerView setHidden:NO];
        [self.tableView setTableHeaderView:self.headerView];
        [self.headerView setBanner:result.bannerList];
        [self.headerView setHidden:NO];
    }else{
        [self.headerView setHidden:YES];
    }
    
    if(result.supplierList.count){
        [self.emptyView setHidden:YES];
        [_allFrames removeAllObjects];
        [_allFrames addObjectsFromArray:[self itemArrayWitFrames:result.supplierList]];
    }else{
         [self showEmptyView];
    }
    
    [self.tableView reloadData];
}

/**
 *  根据模型数组 转成 frame模型数据
 *
 *  @param suppers 商家
 *
 *  @return allFrames
 */
- (NSArray *)itemArrayWitFrames:(NSArray *)suppers
{
    NSMutableArray *frames = [NSMutableArray array];
    for (int i = 0; i<suppers.count; i++) {
        NSArray *prodList = [suppers[i] prodList];
        
        NSMutableArray *childFrames = [NSMutableArray array];
        for (YSCartProduct *prod in prodList) {
            YSCartItemFrame *frame = [[YSCartItemFrame alloc] init];
            // 传递模型数据，计算所有子控件的frame
            frame.product = prod;
            frame.supplier = suppers[i];
            [childFrames addObject:frame];
        }
        [frames addObject:childFrames];
    }
    return frames;
}

#pragma  mark - UITableViewDataSource,UITableViewDelegate

/**
 *  返回一共有多少组
 *
 *  @param tableView
 *
 *  @return
 */
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return  _allFrames.count;
}

/**
 *  返回每一组有多少个
 *
 *  @param tableView
 *  @param section
 *
 *  @return
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_allFrames[section] count];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    YSCartBusinessHeaderView *headerView = [YSCartBusinessHeaderView headerView];
    headerView.statusBtn.tag = section;
    [headerView.statusBtn addTarget:self action:@selector(businessStatusClick:) forControlEvents:UIControlEventTouchUpInside];
    headerView.tag = section;
    if(_result.supplierList.count){
     [headerView setSupplier:_result.supplierList[section]];
    }
    UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headViewClick:)];
    [headerView addGestureRecognizer:singleTap1];
    return headerView;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return YSCartBusinessHeaderViewHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 10)];
    [footerView setBackgroundColor:PUBLIC_BG];
    return footerView;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    YSCartCell *cell =  [YSCartCell cellWithTableView:tableView];
    [cell.cartItemView.calcView setDelegate:self];
     cell.cartItemView.calcView.path = indexPath;
     cell.selectionStyle = UITableViewCellSelectionStyleNone;
     cell.cartItemFrame = self.allFrames[indexPath.section][indexPath.row];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = [_allFrames[indexPath.section][indexPath.row] cellHeight];
    return height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   YSProductDetailCtrl *ctrl = [[YSProductDetailCtrl alloc]initWithProdId:[self.allFrames[indexPath.section][indexPath.row] product].prodMainId];
    [self.navigationController pushViewController:ctrl animated:YES];
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSInteger prodId =  [[_allFrames[indexPath.section][indexPath.row] product] prodId];
        [YSClubDataTool deleteCartWithParam:prodId success:^(BaseResponse *result) {
//            if(result.isSucc){
//                NSLog(@"section = %ld,row = %ld",indexPath.section,indexPath.row);
//                if([_allFrames[indexPath.section] count] == 1){
//                    [_result.supplierList removeObjectAtIndex:indexPath.section];
//                    [_allFrames removeObjectAtIndex:indexPath.section];
//                    [_tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
//                }else{
//                    [[_result.supplierList[indexPath.section] prodList]removeObjectAtIndex:indexPath.row];
//                    [_allFrames[indexPath.section] removeObjectAtIndex:indexPath.row];
//                    [_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//                }
//                [self calcCartCurrentSelectProductWithPrice];
//                
//                if(!_result.supplierList.count){//删光了
//                     [self showEmptyView];
//                }
//            }else{
//                ShowEnterTips(result.data);
//            }
            if(result.isSucc){
                [self requestData];
                [self.tableView reloadData];
                [self calcCartCurrentSelectProductWithPrice];
            }else{
                ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            ShowTips(kRequestFailure);
        }];
    }
}

/**
 *  条目内商品数量改变的回调
 *
 *  @param oldNum   原数量
 *  @param newNum   新数量
 *  @param position 位置
 *  @param calcView 计算器
 */
-(void)numChange:(NSUInteger)oldNum newNum:(NSUInteger)newNum calcView:(CalcView *)calcView{
    
    NSLog(@"原数量:%ld----现数量:%ld----位置:第%ld组，第%ld条",(unsigned long)oldNum,(unsigned long)newNum,(long)calcView.path.section,(long)calcView.path.row);
    
    if(newNum == 0){// 数量为0时
        [self assertDeleteProd:calcView indexPath:calcView.path];
        return;
    }
    
    /*else if (newNum > 20) {// 单品最多20件
        [calcView setNum:20];
        [self calcCartCurrentSelectProductWithPrice];
        ShowTips(@"商品数量超过20个!");
        return;
    }*/
    
    //实时更新条目商品的数量
    NSInteger prodId = [[ _allFrames[calcView.path.section][calcView.path.row] product] prodId];
    [calcView setUserInteractionEnabled:NO];
    [YSClubDataTool addCartWithParam:prodId prodCount:newNum type:0 success:^(BaseResponse *result) {
        [calcView setUserInteractionEnabled:YES];
        if(result.isSucc){
            [[ _allFrames[calcView.path.section][calcView.path.row] product]setProdCount:newNum];
            [self calcCartCurrentSelectProductWithPrice];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        [calcView setUserInteractionEnabled:YES];
    }];
}

/**
 *  判断是否删除商品
 *
 *  @param calcView 计算器view
 *  @param position 当前在tableView中的位置
 */
-(void)assertDeleteProd:(CalcView *)calcView indexPath:(NSIndexPath *)path
{
    _alert = nil;
    _alert = [[UIAlertView alloc]initWithTitle:@"确认删除商品?" message:@"" delegate: self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    
    objc_setAssociatedObject(_alert, (__bridge const void *)(kCartIndexPathObj), path, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    [_alert show];
}

/**
 *  当AlertView的隐藏动画结束的时候进行回调
 *
 *  @param alertView   alertView
 *  @param buttonIndex
 */
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSIndexPath *path = objc_getAssociatedObject(alertView, (__bridge const void *)(kCartIndexPathObj));
        NSInteger prodId =  [[_allFrames[path.section][path.row] product] prodId];
        
        [YSClubDataTool deleteCartWithParam:prodId success:^(BaseResponse *result) {
            if(result.isSucc){
                [self requestData];
                [self.tableView reloadData];
                [self calcCartCurrentSelectProductWithPrice];
            }else{
                ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            ShowTips(kRequestFailure);
        }];
    }
}

/**
 *  点击商户的状态选择
 *
 *  @param btn
 */
-(void)businessStatusClick:(UIButton *)btn {
    NSInteger section =  btn.tag;
    NSLog(@"section----%ld",(long)section);
    
    YSSupplier *supplier = _result.supplierList[section];
    BOOL status = supplier.status;
    [supplier setStatus:!status];
    for (YSCartProduct *prod in supplier.prodList) {
        [prod setStatus:supplier.status];
    }
    
    NSArray *suppliers  =  _result.supplierList;
    for (YSSupplier *supplier in suppliers) {
        if(!supplier.status){
            [self.bottomBar.statusBtn setSelected:NO];
            break;
        }else{
            [self.bottomBar.statusBtn setSelected:YES];
        }
    }
    
    [self calcCartCurrentSelectProductWithPrice];
    [self.tableView reloadData];
}

/**
 *  点击商家的条目
 */
-(void)headViewClick:(UITapGestureRecognizer *)sender{
    NSLog(@"headViewClick----%ld",(long)sender.view.tag);
    YSSupplier *supplier =   _result.supplierList[sender.view.tag];
    NSInteger supplierId =   supplier.supplierId;
    NSLog(@"跳转商家----id:%ld",supplierId);
    YSBusinessCtrl *ctrl =  [[YSBusinessCtrl alloc]initWithSupplierId:supplierId];
    [self.navigationController pushViewController:ctrl animated:YES];
}

/**
 *  计算购物篮当前选中的商品的价格
 */
-(void)calcCartCurrentSelectProductWithPrice{
    
    float currentPrice = 0;
    NSArray *suppliers  =  _result.supplierList;
    for (YSSupplier *supplier in suppliers) {
        NSArray *prods = supplier.prodList;
        for (YSCartProduct *prod in prods) {
            if(prod.status){
                if(prod.prodPromotion&&prod.prodPromotion.price){
                    currentPrice += prod.prodPromotion.price * prod.prodCount;
                }else{
                    currentPrice += prod.prodNewPrice * prod.prodCount;
                }
            }
        }
    }
    [self.bottomBar setPrice:currentPrice];
}

/**
 *  条目的选择状态发生改变回调
 *
 *  @param notif
 */
-(void)itemStatusChange:(NSNotification *)nortif{
    NSIndexPath *indexPath = [nortif object];
    YSCartItemFrame *itemFrame = _allFrames[indexPath.section][indexPath.row];
    YSSupplier *supplier = [itemFrame supplier];
    NSArray *prods = supplier.prodList;
    
    for (YSCartProduct *prod in prods) {
        if(!prod.status){
            [supplier setStatus:prod.status];
            break;
        }else{
            [supplier setStatus:prod.status];
        }
    }
    
    NSArray *suppliers  =  _result.supplierList;
    for (YSSupplier *supplier in suppliers) {
        //处理底部栏全部状态按钮是否选中
        if(!supplier.status){
            [self.bottomBar.statusBtn setSelected:NO];
            break;
        }else{
            [self.bottomBar.statusBtn setSelected:YES];
        }
    }
    [self.tableView reloadData];
    [self calcCartCurrentSelectProductWithPrice];
}

-(void)toHomeCtrl:(NSNotification *)nortif{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self updateCartIndex];
}

-(void)updateCartIndex{
    if(ISLOGIN){
        [[YSCommonReqTool sharedTool] loadIndex:YSBadgeCartType callback:^(NSInteger count) {
        }];
    }else{
        [DefaultsHelper setInteger:0 forKey:kCartIndex];
    }
}


@end
